using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponControllerStab : WeaponControllerBase
{
    [Header("----- 后坐力设置 -----")]
    [SerializeField] protected float recoilDuration;
    [SerializeField] protected float recoilDistance;
    [SerializeField] protected float stabDistance;
    [SerializeField] private float goHitEnemySpeed;
    

    protected override void WeaponPeformAttack(Vector2 attackDirection)
    {
        base.WeaponPeformAttack(attackDirection);

        weaponAttackCo ??= StartCoroutine(GoHitTargetCo(attackDirection));
    }

    private IEnumerator GoHitTargetCo(Vector2 attackDirection)
    {
        canAiming = false;
        //武器移动的距离
        Vector2 posOffset = -attackDirection * recoilDistance;
        //武器目标移动位置（局部坐标）
        Vector2 recoilPos = new(transform.localPosition.x + posOffset.x, transform.localPosition.y + posOffset.y);
        Vector2 targetEnemyPos = attackDirection * stabDistance;
        float timer = 0;

        //武器初始位置
        Vector2 originLocalPos = transform.localPosition;

        //武器后座力效果（只有后退效果）
        while (timer < recoilDuration)
        {
            transform.localPosition = Vector2.Lerp(originLocalPos, recoilPos, timer / recoilDuration);
            timer += Time.deltaTime;
            yield return null;
        }
        transform.localPosition = recoilPos;

        Vector2 startLocalPos = transform.localPosition;
        float totalDistance = Vector2.Distance(startLocalPos, targetEnemyPos);
        float duration = totalDistance / goHitEnemySpeed; // 计算总移动时间
        float elapsed = 0;

        //刺向敌人效果
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float progress = elapsed / duration; // 0到1的进度
            
            //进度值前期增长快，后期增长慢
            float easeProgress = 1 - Mathf.Pow(1 - progress, 2);
            
            // 计算当前位置
            transform.localPosition = Vector2.Lerp(startLocalPos, targetEnemyPos, easeProgress);
            yield return null;
        }
        transform.localPosition = targetEnemyPos;

        yield return new WaitForSeconds(.05f);

        totalDistance = Vector2.Distance(originLocalPos, targetEnemyPos);
        duration = totalDistance / goHitEnemySpeed; // 计算总移动时间
        elapsed = 0;

        //移动到初始位置
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float progress = elapsed / duration;
            
            // 进度值前期增长快，后期增长慢
            float easeProgress = 1 - Mathf.Pow(1 - progress, 2);
            
            // 计算当前位置
            transform.localPosition = Vector2.Lerp(targetEnemyPos, originLocalPos, easeProgress);
            yield return null;
        }
        transform.localPosition = originLocalPos;

        weaponAttackCo = null;
        canAiming = true;
    }
}
